import MainViewUI = layaUI.Main.MainViewUI;

class MainView extends MainViewUI{
    private static _instance:MainView;//单例
    /**
     * 获取 单例
     */
    public static getInstance():MainView{
        if(MainView._instance == null){
            MainView._instance = new MainView();
        }
        return MainView._instance;
    }

    private
    constructor() {
        super();
        this.btnPre.on(Laya.Event.CLICK,this,this.onPre);
        this.btnNext.on(Laya.Event.CLICK,this,this.onNext);
        this.list.renderHandler = new Handler(this,this.onRender);
        //重置第一页
        this._nowPage = 1;

        this.init();
    }

    private _nowPage:number;//当前页
    private _maxPage:number;//最大页

    public selectIndex:number = 0;
    private ethCarArray:Array<data.EthCar> = [];
    private init():void{
        this.ethCarArray = LocalData.EthCarList_EthCar;
    }

    public open():void{
        UIManager.uiLayer.addChild(MainView.getInstance());
        this.list.array = this.ethCarArray;
    }

    public close():void{
        MainView.getInstance().removeSelf();
    }

    private onPre(e:Laya.Event):void{
        var page:number = this._nowPage - 1;
        if(page <= 0){
            return;
        }
        this.updatePage(page);
    }

    private onNext(e:Laya.Event):void{
        var page:number = this._nowPage + 1;
        if(page > this._maxPage){
            return;
        }
        this.updatePage(page);
    }

    private updatePage(page:number):void{
        this._maxPage = Math.ceil(this.ethCarArray.length / 5);
        this._nowPage = page;
        //分页
        var startIndex:number = (page - 1) * 5;
        var endIndex:number = startIndex + 5;
        var maxIndex:number = this.ethCarArray.length;
        endIndex = endIndex > maxIndex ? maxIndex : endIndex;
        this.list.array = this.ethCarArray.slice(startIndex,endIndex);
    }

    private onRender(cell:MainItem,index:number):void{
        cell.setData(cell.dataSource,index);
        if(index == this.selectIndex){
            this.selectIndexItem(cell,index);
        }
    }

    private selectItem:MainItem;
    public selectIndexItem(item:MainItem,index:number):void{
        if(this.selectItem){
            this.selectItem.btn.selected = false;
        }
        this.selectItem = item;
        this.selectIndex = index;
        this.selectItem.btn.selected = true;
        Global.car.setCarSkin("res/LayaScene_car/"+item.ethCar.ID+".lh");
    }
}
